<template>
  <div class="fx-column">
    <el-upload
      ref="upload"
      list-type="picture-card"
      :action="uploadAction"
      :headers="headerSetting"
      :on-change="handlePictureChanged"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :on-success="handleSuccess"
      :multiple="false"
      :auto-upload="false"
      class="img-upload-container"
      :class="{'el-upload-hidden': !addEnable}">
      <i class="el-icon-plus"></i>
    </el-upload>
    <image-upload-form ref="form" :form-options="formOptions" :location-type="locationType"></image-upload-form>
    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>

import {mapGetters} from "vuex";
import {getToken} from "@/utils/auth";
import ImageUploadForm from "@/components/ImageUpload/form";

export default {
  name: 'image-upload',
  components: {ImageUploadForm},
  props: {
    locationType: {
      type: Number | String,
      default: ''
    },
    formOptions: {
      type: Object,
      default: () => ({
        companyname: '',
        sort_id: ''
      })
    }
  },
  data() {
    return {
      headerSetting: {'Authorization': getToken()},
      dialogImageUrl: '',
      dialogVisible: false,
      fileList: [],
    };
  },
  computed: {
    ...mapGetters(['authenticate']),
    addEnable() {
      // 只允许添加1个
      return !this.fileList.length
    },
    uploadAction() {
      const auth = this.authenticate
      const name = this.formOptions.companyname || 'default'
      const sort = this.formOptions.sort_id || 0
      const params = `account=${auth.account}&locationType=${this.locationType}&sort_id=${sort}&companyname=${name}`
      return '/api/User/UploadFile?' + params
    }
  },
  methods: {
    handlePictureChanged(file, fileList) {
      this.fileList = fileList
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleSuccess() {
      this.$emit('success')
    },
    async submit() {
      await this.$refs.form.validate()
      return this.$refs.upload.submit()
    }
  }
}
</script>

<style scoped>
/deep/ .el-upload-hidden .el-upload--picture-card {
  display: none; /* 上传按钮隐藏, disabled的控制效果不好 */
}

/deep/ .el-upload-list--picture-card, .img-upload-container {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
